package com.yanghui.dtracing.core.config;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.yanghui.dtracing.core.exception.DTracerException;
import com.yanghui.dtracing.core.opentracing.sampler.SamplerProperties;

import java.util.Arrays;

public class ConfigParser {
	
	public static AgentConfig parseAgentArgs(String agentArgs) {
		AgentConfig agentConfig = new AgentConfig();
		fromEnv(agentConfig);
		try {
			if(agentArgs == null) {
				return agentConfig;
			}
			String[] argArr = agentArgs.split("&");
			for(String arg : argArr) {
				if(!arg.contains("=")) {
					continue;
				}
				String[] kv = arg.split("=");
				if(kv == null || kv.length != 2) {
					continue;
				}
				if(AgentConfig.AGENT_LOG_PATH.equalsIgnoreCase(kv[0])){
					agentConfig.setLogPath(kv[1]);
				}
				if(AgentConfig.AGENT_LOG_LEVEL.equalsIgnoreCase(kv[0])) {
					agentConfig.setLogLevel(kv[1]);
				}
				if(AgentConfig.EXCLUDE_PLUGIN_LIST.equalsIgnoreCase(kv[0])){
					String excludeAgentListStr = kv[1];
					if(!"".equals(excludeAgentListStr.trim())){
						String[] excludeAgentListArr = excludeAgentListStr.toLowerCase().split(",");
						agentConfig.getExcludePluginList().addAll(Arrays.asList(excludeAgentListArr));
					}
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return agentConfig;
	}

	private static void fromEnv(AgentConfig agentConfig){
		try{
			SamplerProperties samplerProperties = new SamplerProperties();
			String percentageStr = System.getProperty(AgentConfig.SAMPLER_PERCENTAGE);
			if(NumberUtil.isInteger(percentageStr)){
				samplerProperties.setPercentage(Integer.valueOf(percentageStr));
			}
			agentConfig.setSamplerProperties(samplerProperties);
			String serviceName = System.getProperty(AgentConfig.SERVICE_NAME);
			if(StrUtil.isEmpty(serviceName)){
				throw new DTracerException("service name is not empty,Please add the following to the JVM startup parameters:-Dservice.name=xxx");
			}
			agentConfig.setServiceName(serviceName);
		}catch (DTracerException e){
			throw e;
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
